package com.apes.fn.scm.retailReturn;

import com.alibaba.fastjson.JSONObject;
import com.apes.fn.crm.customerExpand.FnCustomerExpand;
import com.apes.fn.scm.retailOrder.model.RetailOrder;
import com.apes.fn.scm.retailOrder.model.RetailOrderItem;
import com.apes.fn.scm.retailOrder.repository.RetailOrderRepository;
import com.apes.fn.server.servicePlan.service.ServicePlanceService;
import com.apes.framework.api.DomainService;
import com.apes.framework.api.SpringManager;
import com.apes.framework.jpa.generator.service.SequenceService;
import com.apes.framework.jpa.spec.JpaDsl;
import com.apes.framework.plugin.esb.api.SimpleRequest;
import com.apes.framework.plugin.event.Listener;
import com.apes.framework.plugin.todo.TodoTaskService;
import com.apes.framework.util.DateUtil;
import com.apes.framework.util.LogicalUtil;
import com.apes.framework.util.MapUtil;
import com.apes.scm.account.account.service.ProductAccountService;
import com.apes.scm.account.transit.DepositInTransitService;
import com.apes.scm.masterdata.frame.model.Store;
import com.apes.scm.masterdata.frame.repository.StoreRepository;
import com.apes.scm.masterdata.party.model.PartyRole;
import com.apes.scm.masterdata.product.model.Product;
import com.apes.scm.stock.transfer.model.Pick;
import com.apes.scm.stock.transfer.model.PickItem;
import com.apes.scm.stock.transfer.repository.PickRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;

@Service("retailReturnWithOrderService")
public class RetailReturnWithOrderService extends DomainService {

    @Autowired
    private RetailReturnRepository retailReturnRepository;
    @Autowired
    private ProductAccountService productAccountService;
    @Autowired
    private RetailOrderRepository retailOrderRepository;
    @Autowired
    private SequenceService sequenceService;


    /**
     * 功能: 创建
     * @param request
     * @returns
     */
    public RetailReturn create(SimpleRequest request) {
        RetailReturn retailReturn = request.getO(RetailReturn.class);

        // 进行数据检查，判断是否能进行退货
        checkReturn(retailReturn);

        // 获取退货单号
        String companyId = request.getCurrentCompany() == null ? "" : ((PartyRole) request.getCurrentCompany()).getId();
        retailReturn.setId("LT" + companyId + sequenceService.getId(RetailReturn.CONST_TABLE_NAME));

        // 客户信息处理
        PartyRole customer = retailReturn.getCompany().getParty().getPartyRoles().stream()
                .filter(partyRole -> "Customer".equals(partyRole.getRole().getId()))
                .findFirst().orElse(null);
        if (customer != null) {
            retailReturn.setCustomer(customer);
        }
        JSONObject tempJson = request.getJO();
        FnCustomerExpand customerExpand = this.invoke("fn.customerExpand.updateOrInsert", MapUtil.mapper("customerCar", tempJson.get("customerCar")));
        retailReturn.setCustomerExpand(customerExpand);

        PartyRole creator = getPerson(request);
        retailReturn.setCreator(creator.getId());    // 增加创建人
        return save(retailReturn);
    }

    private void checkReturn(RetailReturn retailReturn){
        // 判断明细是否为空
        if (retailReturn.getSaleItems().size() == 0) throw new RuntimeException("退货明细不能为空！");
        if (retailReturn.getSaleOrder() == null) throw new RuntimeException("原销售订单号为空！");

        //发票限制
        if (retailReturn.getSaleOrder().getInvoicedAmount() != 0) throw new RuntimeException("该零售单已开发票，如需冲红请联系财务收回发票号码！");

        // 银联车主平台渠道的零售单, 不能发起零售有单退货；
        if ("130".equals(retailReturn.getSaleOrder().getChannel().getId())) throw new RuntimeException("银联车主平台渠道的零售单, 不能发起零售有单退货");

        /* 主表中的数据控制 */
        if(retailReturn.getSaleOrder().getChannel() == null) throw new RuntimeException("年卡类商品不允许退款,请在APP操作退款");

        if(ServicePlanceService.PLATFORM_OUT_ORDER.contains(retailReturn.getSaleOrder().getChannel().getName() )) {
            String name = retailReturn.getSaleOrder().getSaleItems().stream().findFirst().get().getProduct().getName();
            throw new RuntimeException( name + "该单据属于定制款商品，不允许在erp发起退货退款操作，如在质保期内出现质量问题，可前往黑盒订单详情页查看质保单号，将质保单号提供给中转站进行售后处理");
        }

        if ("detectReport".equals(retailReturn.getSaleOrder().getOrderType())) {
            throw new RuntimeException("原销售订单是新能源车电池检测报告，不允许退款");
        }

//        if("45".equals(retailReturn.getSaleOrder().getChannel().getId()))throw new RuntimeException("该单据属于建行生活，无法发起退款");


        // 检查商品是否为提单冲红，如果是提单冲红需要检查交货单是否发货，发货的交货单不能提单冲红
        long deliveringCount = retailReturn.getSaleItems().stream()
                .filter(retailReturnItem -> retailReturnItem.getQtyDelivering() > 0 && retailReturnItem.getRetailOrderItem().getProductRule() == 0).count();
        if (deliveringCount > 0) {
            List<Pick> picks = SpringManager.getBean(PickRepository.class).findByOriginAndState(retailReturn.getSaleOrder().getId(), "done");
            if (!picks.isEmpty()) throw new RuntimeException("零售单已发货，请重新做退货单！");
        }

        // 中石化门店不能隔天退款
//        Optional.ofNullable(retailReturn.getDept()).orElseThrow( () -> new RuntimeException("当前零售退回的部门信息为空，请检查！"));
//        Store store = SpringManager.getBean(StoreRepository.class).findByDept(retailReturn.getDept());
//        if (store.isSinopec() && DateUtil.dateCompare( retailReturn.getSaleOrder().getCreateDate(), new Date()) != 0) {
//            throw new RuntimeException("中石化门店订单不能隔天退款!");
//        }


        /* 明细表中的数据控制 */
        retailReturn.getSaleItems().forEach(
                retailReturnItem -> {
                    Product product = retailReturnItem.getProduct();
                    if (product.queryServeType().getId().equals("010")) {
                        throw new RuntimeException(String.format("年卡类商品[%s][%s]不允许退款", retailReturnItem.getProduct().getId(), retailReturnItem.getProduct().getName()));
                    }
                    if (product.getClassify().getId().equals("S01090201001")) {
                        throw new RuntimeException("会员储值商品，请到APP做退款");
                    }

                    if (LogicalUtil.in(product.getId(), "0002935072", "0002935068")) {
                        throw new RuntimeException("e保养+ 商品，请到APP做退款");
                    }
                });
    }

    /***
     * 功能: 创建
     * @param retailReturn
     * @returns
     */
    public RetailReturn save(RetailReturn retailReturn) {
        retailReturn.computeAmt(); // 合计金额
        retailReturn.setInvoiceStatus("no");
        retailReturn.setState("sent");

        setQtyReturning(retailReturn, 1.00); // 回写零售订单退货中数量
        frost(retailReturn, 1.00);   // 冻结交货单(针对未发货数量)

        // 退货单做单时界面是取的商品的税率，需要取原零售单商品的税率
        retailReturn.getSaleItems().forEach( retailReturnItem -> {
            retailReturnItem.setTax(retailReturnItem.getRetailOrderItem().getTax());
        });

        return retailReturnRepository.saveAndFlush(retailReturn);
    }

    private void checkData(SimpleRequest request) {
        String id = request.get("id");
        RetailReturn saleReturn = retailReturnRepository.findOne(id);
        if (saleReturn == null) throw new RuntimeException("订单：" + id + " 在系统中不存在。");
        if (saleReturn.getVersion() != (int) request.get("version")) throw new RuntimeException("记录已更新或已删除，请重新提交！");
        if (saleReturn.getState().equals("confirmed")) throw new RuntimeException("订单：" + id + " 在系统中已审批。");
    }

    /***
     * 功能： 修改
     * @param request
     * @return
     */
    public RetailReturn update(SimpleRequest request) {
        checkData(request);
        RetailReturn retailReturn = request.getO(RetailReturn.class);
        retailReturn.getSaleItems().stream().forEach(retailReturnItem -> {
            if (retailReturnItem.getProduct().queryServeType().getId().equals("010")) {
                throw new RuntimeException(String.format("年卡类商品[%s][%s]不允许退款", retailReturnItem.getProduct().getId(), retailReturnItem.getProduct().getName()));
            }
        });
        //发票限制
        if (retailReturn.getSaleOrder().getInvoicedAmount() != 0) {
            throw new RuntimeException("该零售单已开发票，如需冲红请联系财务收回发票号码！");
        }
        RetailReturn oldRetailReturn = retailReturnRepository.findOne(retailReturn.getId());

        // 分销订单退货中数量释放与写入
        setQtyReturning(oldRetailReturn, -1.00);
        setQtyReturning(retailReturn, 1.00);

        retailReturn.computeAmt(); // 合计金额

        // 交货单的解冻与冻结(针对未发货数量)
        frost(oldRetailReturn, -1.00);
        frost(retailReturn, 1.00);

        // 退货单做单时界面是取的商品的税率，需要取原零售单商品的税率
        retailReturn.getSaleItems().forEach( retailReturnItem -> {
            retailReturnItem.setTax(retailReturnItem.getRetailOrderItem().getTax());
        });

        return retailReturnRepository.saveAndFlush(retailReturn);
    }

    /***
     * 功能：删除
     * @param request
     * @return
     */
    public String delete(SimpleRequest request) {
        RetailReturn saleReturn = request.getO(RetailReturn.class);
        saleReturn = retailReturnRepository.findOne(saleReturn.getId());
        if (saleReturn == null) throw new RuntimeException("订单：" + request.get("id") + " 在系统中不存在。");
        if (!saleReturn.getState().equals("sent"))
            throw new RuntimeException("订单：" + request.get("id") + " 在系统中已审批。");

        // 解冻交货单(针对未发货数量)
        frost(saleReturn, -1.00);

        // 分销订单退货中数量释放
        setQtyReturning(saleReturn, -1.00);

        //删除单据对应待办
        SpringManager.getBean(TodoTaskService.class).finishTask(saleReturn);

        retailReturnRepository.delete(saleReturn);
        return "删除成功";
    }



    /***
     * 功能：审核
     * @param request
     * @return
     */
    public RetailReturn approve(SimpleRequest request) {
        checkData(request);
        RetailReturn saleReturn = request.getO(RetailReturn.class);

        // 加可用数(针对未发货数量)
        saleReturn.getSaleItems().forEach((saleReturnItem -> {
            if (saleReturnItem.getQtyDelivering() > 0 && checkPicked(saleReturnItem)) {
                productAccountService(saleReturn, saleReturnItem, 1.00, "分销提单冲红");
            }
        }));

        setQtyReturned(saleReturn);

        // 交货单先解冻 后终止(针对未发货数量)
        frost(saleReturn, -1.00);
        pickCancel(saleReturn);

        // 中石化门店状态控制
        Store store = SpringManager.getBean(StoreRepository.class).findByDept(saleReturn.getDept());
        if ( store.isSinopec() ) {
            // 中石化门店
            saleReturn.setState("sinopecReturn");
            saleReturn.setDateSinopecReturn(new Date());
            saleReturn.setApproveUID(getPerson(request));

            // 发起APP 中石化退款
            appRefund(saleReturn, 1);  // 多传入APP 一个参数来判断，是否为中石化退款
            return retailReturnRepository.saveAndFlush(saleReturn);
        } else {
            // 非中石化门店
            saleReturn.setApproveUID(getPerson(request));
            return approved(saleReturn);
        }
    }

    private RetailReturn approved(RetailReturn saleReturn) {
        saleReturn.setState("confirmed");
        saleReturn.setDateApprove(new Date());
        RetailReturn nSaleReturn = retailReturnRepository.saveAndFlush(saleReturn);

        nSaleReturn.setShipped();   // 判断订单是否完成
        nSaleReturn.checkShip();    // 如果无需发货直接设置退款状态
        if (nSaleReturn.getState().equals("refund")) nSaleReturn = retailReturnRepository.saveAndFlush(nSaleReturn);

        /**未达帐**/
        SpringManager.getBean(RetailReturnNoOrderService.class).saveDepositInTransit(nSaleReturn);
        return nSaleReturn;
    }

    /**
     * APP 确认中石化退款完成
     * @param request {"id" : ""}
     * @return RetailReturn
     */
    public RetailReturn sinopecRefund(SimpleRequest request){
        String id = request.get("id");
        RetailReturn retailReturn = retailReturnRepository.findOne(id);
        return approved(retailReturn);
    }

    /**
     * 可用数（仅仅处理提单冲红）
     */
    private void productAccountService(RetailReturn saleReturn, RetailReturnItem saleReturnItem, Double unit, String remarks) {
        productAccountService.setProductAvailable(saleReturnItem.getProduct(),
                saleReturnItem.getLocation(), saleReturnItem.getUom(), unit * saleReturnItem.getQtyDelivering(),
                saleReturn.getInnerBusinessType(), saleReturn.getId(), saleReturnItem.getId(), remarks, saleReturn.getCompany());
        /**未达帐**/
        DepositInTransitService depositInTransitService = SpringManager.getBean(DepositInTransitService.class);
        /**删除未达帐**/
        depositInTransitService.delete(saleReturn.getInnerBusinessType(), saleReturn.getInnerBusinessKey(),
                saleReturnItem.getId(), saleReturnItem.getLocation());
    }

    /**
     * 回写销售订单中：退货数量（退货中/已退货）
     *
     * @param retailReturn
     * @param unit
     */
    private void setQtyReturning(RetailReturn retailReturn, Double unit) {
        // 获取到原订单
        RetailOrder retailOrder = retailReturn.getSaleOrder();
        retailReturn.getSaleItems().stream().forEach(saleReturnItem -> {
            // 获取到原订单行
            RetailOrderItem retailOrderItem = retailOrder.getSaleItems().stream().filter(
                    item -> item.getId().equals(saleReturnItem.getRetailOrderItem().getId())
            ).findFirst().get();

            if (unit != null) {
                saleReturnItem.sumProductUomQty();
                retailOrderItem.sumQtyReturning(unit * saleReturnItem.getQtyDelivering(), unit * saleReturnItem.getQtyDelivered());
            } else {
                // 释放提单冲红数量 退货冲红数量  写入退货数量 提单冲红数量写入取消数量
                retailOrderItem.sumQtyReturning(-1 * saleReturnItem.getQtyDelivering(), -1 * saleReturnItem.getQtyDelivered());
                retailOrderItem.calcQtyReturned(saleReturnItem.getProductUomQty());
                retailOrderItem.cancle(saleReturnItem.getQtyDelivering());
                retailOrder.checkQtyReturned();
            }
        });
        // unit == null 时表示审核
        // 审核时 saveAndFlush 用于触发零售单的场景流，用于处理提单冲红导致标准零售流程报错
        if (unit == null && retailReturn.getSaleItems().stream().mapToDouble(RetailReturnItem::getQtyDelivering).sum() != 0d) {
            //只有当天生成的正单退货时才会重推事务发件箱，防止营业额明细统计早期数据
            LocalDate retailReturnDate = DateUtil.UDateToLocalDate(retailReturn.getCreateDate());
            LocalDate retailOrderDate = DateUtil.UDateToLocalDate(retailOrder.getCreateDate());
            long days = Math.abs(retailReturnDate.toEpochDay() - retailOrderDate.toEpochDay());
            if(days == 0) retailOrderRepository.saveAndFlush(retailOrder);
        } else {
            retailOrderRepository.save(retailOrder);
        }
    }

    private void setQtyReturned(RetailReturn retailReturn) {
        setQtyReturning(retailReturn, null);
    }

    /**
     * 交货单冻结/解冻(提单冲红数量)
     *
     * @param retailReturn
     * @param unit
     */
    private void frost(RetailReturn retailReturn, Double unit) {
        JSONObject tempJson = new JSONObject();

        tempJson.put("id", retailReturn.getSaleOrder().getId());
        tempJson.put("innerBusinessType", retailReturn.getSaleOrder().getInnerBusinessType());

        //存在无库存的情况
        List<Map> items = retailReturn.getSaleItems().stream()
                .filter(saleReturnItem -> saleReturnItem.getQtyDelivering() > 0 && checkPicked(saleReturnItem))
                .map(saleReturnItem -> {
                    Map map = new HashMap();
                    map.put("id", saleReturnItem.getRetailOrderItem().getId());
                    map.put("frostQty", unit * saleReturnItem.getQtyDelivering());
                    return map;
                }).collect(Collectors.toList());
        if (items.size() == 0) return;
        tempJson.put("items", items);

        // 调用 交货单的冻结
        this.invoke("stock.pick.frost", tempJson);
    }

    /**
     * 交货单终止
     *
     * @param saleReturn
     */
    private void pickCancel(RetailReturn saleReturn) {
        JSONObject tempJson = new JSONObject();
        tempJson.put("id", saleReturn.getSaleOrder().getId());
        tempJson.put("innerBusinessType", saleReturn.getSaleOrder().getInnerBusinessType());
        /**未达帐**/
        DepositInTransitService depositInTransitService = SpringManager.getBean(DepositInTransitService.class);
        List<Map> items = saleReturn.getSaleItems().stream()
                .filter((saleReturnItem) -> saleReturnItem.getQtyDelivering() > 0 && checkPicked(saleReturnItem))
                .map(saleReturnItem -> {
                    Map map = new HashMap();
                    map.put("id", saleReturnItem.getRetailOrderItem().getId());
                    map.put("cancelQty", saleReturnItem.getQtyDelivering());
                    /**删除未达帐**/
                    depositInTransitService.delete(saleReturn.getSaleOrder().getInnerBusinessType(), saleReturn.getSaleOrder().getInnerBusinessKey(),
                            saleReturnItem.getRetailOrderItem().getId(), saleReturnItem.getRetailOrderItem().getLocation());
                    return map;
                }).collect(Collectors.toList());
        if (items.size() == 0) return;
        tempJson.put("items", items);
        this.invoke("stock.pick.cancel", tempJson);
    }

    /**
     * 功能：findOne
     *
     * @param request
     * @return RetailReturn
     */
    public RetailReturn findOne(SimpleRequest request) {
        Map params = MapUtil.mapper("orderType.code", "A", "id", request.get("id"));
        List<RetailReturn> list = retailReturnRepository.findAll(JpaDsl.toCriteria(params));
        if (list != null && list.size() > 0) return list.get(0);
        return null;
    }


    public List<Pick> testCreatePickOrder(SimpleRequest request) {
        String id = request.get("id");
        RetailReturn retailReturn = retailReturnRepository.findOne(id);
        return getPicks(retailReturn);
    }

    /**
     * 功能：创建拣配单
     * 根据仓库汇总
     *
     * @param request
     */
    public List<Pick> createPickOrder(SimpleRequest request) {
        RetailReturn retailReturn = request.getO(RetailReturn.class);
        return getPicks(retailReturn);
    }

    private List<Pick> getPicks(RetailReturn retailReturn) {
        List<Pick> pickList = new ArrayList<>();
        //  根据明细上面的仓库进行汇总数据
        retailReturn.getSaleItems().stream()
                .filter(orderItem -> LogicalUtil.notIn(orderItem.getProduct().getType(), "aut"))
                .collect(groupingBy(RetailReturnItem::getLocation))
                .forEach((location, saleOrderItems) -> {

                    Set<PickItem> pickItems = new HashSet<>();
                    saleOrderItems.forEach(
                            saleItem -> {
                                PickItem pickItem = new PickItem();
                                pickItem.setUom(saleItem.getUom());
                                pickItem.setProduct(saleItem.getProduct());
                                pickItem.setOrderedQty(saleItem.getProductUomQty());
                                pickItem.setProductUomQty(saleItem.getProductUomQty());
                                pickItem.setOriginLine(saleItem.getId());
                                pickItems.add(pickItem);
                            });
                    if (pickItems.isEmpty()) return;

                    Pick pick = new Pick();
                    pick.setMoveType(retailReturn.getMoveType());
                    pick.setPartner(retailReturn.getCustomer());
                    pick.setLocation(location);
                    pick.setCompany(location.getCompany());     // 公司为库区的公司

                    pick.setOrigin(retailReturn.getId());
                    pick.setOriginBusinessType(retailReturn.getInnerBusinessType());
                    pick.setOperation("receipt");               // 交货类型： 收货
                    pick.setScene(retailReturn.getScene());            // 注入场景
                    pick.setPickItems(pickItems);

                    pickList.add(pick);
                });
        return pickList;
    }


    /**
     * 功能：处理收货完成事件
     */
    @Listener(topic = "event:stock.pick.delivery")
    public void delivery(SimpleRequest request) {
        JSONObject param = request.getJO();
        if (!param.getString("originBusinessType").equals(RetailReturn.class.getSimpleName())) return;

        RetailReturn retailReturn = retailReturnRepository.findOne(param.getString("origin"));
        for (Map item : ((List<Map>) param.get("items"))) {
            retailReturn.getSaleItems().stream()
                    .filter(retailReturnItem -> retailReturnItem.getId().equals(item.get("originItemId")))
                    .forEach(retailReturnItem -> {
                        double qtyDone = ((Number) item.get("qtyDone")).doubleValue();
                        // 写入收货数量
                        retailReturnItem.delivery(qtyDone);
                    });
        }
        // 更新交货状态以及单据状态
        retailReturn.setShipped();

        // 用于判断是否触发场景流
        if (retailReturn.getState().equals("confirmed")) retailReturnRepository.save(retailReturn);
        if (retailReturn.getState().equals("refund")) retailReturnRepository.saveAndFlush(retailReturn);
    }

    /**
     * 是否需要发货
     *
     * @param retailReturnItem
     * @return
     */
    private boolean checkPicked(RetailReturnItem retailReturnItem) {
        return retailReturnItem.getRetailOrderItem().getProductRule() == 0;
    }

    /**
     * 退款接口
     *
     * @param request
     */
    public void retailRefund(SimpleRequest request) {
        RetailReturn retailReturn = request.getO(RetailReturn.class);
        RetailReturn retail = retailReturnRepository.findOne(retailReturn.getId());
        appRefund(retail, 0);
    }

    public void repeatRetailRefund(SimpleRequest request){
        String id = request.get("id");
        RetailReturn retail = retailReturnRepository.findOne(id);
        appRefund(retail, 0);
    }

    /**
     * 调用中石化接口退货
     * @param retail RetailReturn
     * @param type 中石化参数 1 表示中石化门店， 0 表示正常退款
     */
    private void appRefund(RetailReturn retail, int type) {
        List<Map> items = new ArrayList<>();
        retail.getSaleItems().forEach(item -> {
            items.add(MapUtil.mapper("goodsCode", item.getProduct().getId(), "goodsName", item.getProduct().getName(),
                    "goodsId", item.getPackId(), "number", item.getProductUomQty(),
                    "salePrice", item.getPriceUnit(), "id", item.getId()));
        });

        Map map = MapUtil.mapper("retailNumber", retail.getSaleOrder() == null ? null : retail.getSaleOrder().getId(),
                "retailRefundNumber", retail.getId(),
                "refundPrice", retail.getAmtTotal(),
                "storeCode", retail.getDept().getId(),
                "operateName", retail.getApproveUID().getName(),
                "reason", retail.getReturnReasons() == null ? "": retail.getReturnReasons().getDescription(),
                "remark", retail.getReturnReason(),
                "mobile", retail.getSaleOrder() == null ? retail.getCustomerExpand().getMobile() : retail.getSaleOrder().getCustomerExpand().getMobile(),
                "carLicense", retail.getSaleOrder() == null ? retail.getCustomerExpand().getCarLicense() : retail.getSaleOrder().getCustomerExpand().getCarLicense(),
                "scene", MapUtil.mapper("id", retail.getScene().getId()),
                "realRefund", retail.getRefund(),
                "sinopecRefund", type,     // 增加中石化参数 1 表示中石化门店， 0 表示正常退款
                "items", items);
        JSONObject response = JSONObject.parseObject(this.invoke("pi.app.ext",
                MapUtil.mapper("headers", MapUtil.mapper("method", "v1/order/retail-refund", "action", "post", "returnHeaders", "true"), "body", map)));

        try {
            if (!response.getJSONObject("body").getBoolean("success")) {
                throw new RuntimeException(response.getJSONObject("body").getJSONObject("data").getString("message"));
            }
        } catch (Exception e) {
            throw new RuntimeException("调用App接口报错:" + e.getMessage());
        }
    }

    /**
     * 退款完成接口
     *
     * @param request
     */
    public void retailDone(SimpleRequest request) {
        RetailReturn retailReturn = retailReturnRepository.findOne((String) request.get("id"));
        retailReturn.setState("done");
        retailReturn.setDateDone(new Date());
        if (retailReturn.getOrderType().getCode().equals("A")) {
            //有原单退货修改方案数量

        }
        retailReturn.setProcessInitiator(retailReturn.getApproveUID().getId());
        retailReturn.setProcessInitiatingDepartment(retailReturn.getDept().getId());
        retailReturnRepository.saveAndFlush(retailReturn);
    }
}
